<script setup>
import { reactive, toRefs, ref, onMounted } from 'vue';
import { ElButton, ElColorPicker, ElDialog, ElForm, ElFormItem, ElInput, ElOption, ElSelect } from 'element-plus';
import { OPERATION_TYPE } from '@/common/js/common-const';

const props = defineProps({
  operationData: {
    type: Object,
  },
  operationType: {
    type: String,
  },
  operationShow: {
    type: Boolean,
  },
  checkedTreeItem: {
    type: Object,
  },
});
const { operationShow, operationType, operationData, checkedTreeItem } = toRefs(props);
const emit = defineEmits(['handleParamEmit', 'handleShowEmit']);

const formRef = ref(null);

const formInline = reactive({
  category: '',
  title: '',
  type: '',
  icon: '',
  bgColor: null,
  borderColor: null,
  layerName: '',
  layerStyle: '',
  bbox: '',
  customFiled: [
    { key: '', value: '' }, // 初始一个空字段
  ],
  sortOrder: 1,
  pid: null,
  categoryName: '',
});

const rules = {
  categoryName: [
    {
      required: true,
      message: '此项为必填项',
      trigger: 'blur',
    },
  ],
  title: [
    {
      required: true,
      message: '此项为必填项',
      trigger: 'blur',
    },
  ],

  type: [
    {
      required: true,
      message: '此项为必填项',
      trigger: 'blur',
    },
  ],
};

const predefineColors = ref([
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
  'rgba(255, 69, 0, 0.68)',
  'rgb(255, 120, 0)',
  'hsv(51, 100, 98)',
  'hsva(120, 40, 94, 0.5)',
  'hsl(181, 100%, 37%)',
  'hsla(209, 100%, 56%, 0.73)',
  '#c7158577',
]);

const closeBoxShowDialog = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  emit('handleShowEmit', false);
};

onMounted(() => {
  formInline.categoryName = checkedTreeItem.value.title;
  formInline.category = checkedTreeItem.value.code;

  if (operationType.value == OPERATION_TYPE.ADD) {
    if (!formRef.value) return;
    formRef.value.resetFields();
  } else if (operationType.value == OPERATION_TYPE.LOOK) {
    formInline.pid = operationData.value.id;
  } else {
    if (Object.keys(operationData.value).length) {
      formInline.title = operationData.value.title;
      formInline.type = operationData.value.type;
      formInline.icon = operationData.value.icon;
      formInline.bgColor = operationData.value.bgColor;
      formInline.borderColor = operationData.value.borderColor;
      formInline.layerName = operationData.value.layerName;
      formInline.layerStyle = operationData.value.layerStyle;
      formInline.bbox = operationData.value.bbox;
      formInline.customFiled = operationData.value.customFiled || {};
      formInline.pid = operationData.value.pid;
      formInline.sortOrder = operationData.value.sortOrder;
    }
  }
});

// 添加新字段
const addField = () => {
  formInline.customFiled.push({ key: '', value: '' });
};

// 删除字段
const removeField = (index) => {
  if (formInline.customFiled.length > 1) {
    formInline.customFiled.splice(index, 1);
  }
};

const handleSubmit = () => {
  formRef.value.validate((err) => {
    if (err) {
      if (formInline?.customFiled == !null || Object.keys(formInline?.customFiled)?.length) {
        formInline.customFiled = formInline.customFiled?.reduce((acc, item) => {
          if (item.key && item.value) {
            acc[item.key] = item.value;
          }

          return acc;
        }, {});
      } else {
        formInline.customFiled = {};
      }

      if (operationType.value == OPERATION_TYPE.ADD || operationType.value == OPERATION_TYPE.LOOK) {
        emit('handleParamEmit', formInline, OPERATION_TYPE.ADD);
      }

      if (operationType.value == OPERATION_TYPE.EDIT) {
        formInline['id'] = operationData.value.id;
        emit('handleParamEmit', formInline, OPERATION_TYPE.EDIT);
      }
    }
  });
};
</script>
<template>
  <div class="user-loading">
    <ElDialog
      v-if="operationShow"
      v-model="operationShow"
      align-center="center"
      :append-to-body="false"
      :title="userType == OPERATION_TYPE.EDIT ? '编辑' : userType == OPERATION_TYPE.ADD ? '新建' : '添加'"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
      @close="closeBoxShowDialog()"
    >
      <main class="max-h-850px overflow-auto">
        <ElForm ref="formRef" :rules="rules" :model="formInline" label-position="top">
          <ElFormItem label="图层分类" prop="categoryName">
            <ElInput v-model.trim="formInline.categoryName" show-word-limit maxlength="50" type="text" disabled />
          </ElFormItem>
          <ElFormItem label="标题" prop="title">
            <ElInput v-model.trim="formInline.title" show-word-limit maxlength="50" type="text" />
          </ElFormItem>
          <ElFormItem label="类型" prop="type">
            <ElSelect v-model="formInline.type" placeholder="请选择" style="width: 100%">
              <ElOption label="DIR(目录)" value="DIR" />
              <ElOption label="LAYER(图层)" value="LAYER" />
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="排序">
            <ElInput v-model.trim="formInline.sortOrder" show-word-limit maxlength="50" type="number" />
          </ElFormItem>
          <ElFormItem label="标识">
            <ElInput v-model.trim="formInline.icon" show-word-limit maxlength="50" type="text" />
          </ElFormItem>
          <ElFormItem label="图层名称">
            <ElInput v-model.trim="formInline.layerName" show-word-limit maxlength="50" type="text" />
          </ElFormItem>
          <ElFormItem label="图层样式">
            <ElInput v-model.trim="formInline.layerStyle" show-word-limit maxlength="50" type="text" />
          </ElFormItem>
          <ElFormItem label="图层四至">
            <ElInput v-model.trim="formInline.bbox" show-word-limit maxlength="200" type="text" />
          </ElFormItem>
          <ElFormItem label="背景颜色">
            <ElColorPicker v-model="formInline.bgColor" show-alpha :predefine="predefineColors" />
          </ElFormItem>
          <ElFormItem label="边框颜色">
            <ElColorPicker v-model="formInline.borderColor" show-alpha :predefine="predefineColors" />
          </ElFormItem>
          <ElFormItem label="自定义字段">
            <div v-for="(item, index) in formInline.customFiled" :key="index" class="custom-field-item">
              <ElInput v-model="item.key" placeholder="键" style="width: 150px; margin-right: 10px"></ElInput>
              <ElInput v-model="item.value" placeholder="值" style="width: 150px; margin-right: 10px"></ElInput>
              <ElButton
                type="danger"
                :disabled="formInline.customFiled.length === 1"
                class="mr-5px"
                @click="removeField(index)"
              >
                删除
              </ElButton>
            </div>
            <ElButton type="primary" @click="addField"> 添加字段 </ElButton>
          </ElFormItem>
        </ElForm>
      </main>
      <div class="dialog-footer">
        <div @click="closeBoxShowDialog()">取消</div>
        <div @click="handleSubmit()">保存</div>
      </div>
    </ElDialog>
  </div>
</template>

<style scoped lang="scss">
.user-loading {
  :deep(.el-dialog) {
    width: 700px;
    border-radius: 6px;
  }

  .dialog-footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 30px;
    text-align: right;
    div {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100px;
      height: 40px;
      font-size: 16px;
      border-radius: 4px;
      cursor: pointer;

      &:first-child {
        color: $base-color-info;
        border: 1px solid #e9e9e9;
      }

      &:nth-child(2) {
        margin: 0 20px;
        color: $base-button-color-white;
        background-color: $base-button-color-add;
      }
    }
  }
}
</style>
